package com.mmall.service.impl;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.mmall.common.Const;
import com.mmall.common.ResponseCode;
import com.mmall.common.ServerResponse;
import com.mmall.dao.CartMapper;
import com.mmall.dao.ProductMapper;
import com.mmall.pojo.Cart;
import com.mmall.pojo.Product;
import com.mmall.service.ICartService;
import com.mmall.util.BigDecimalUtil;
import com.mmall.vo.CartProductVo;
import com.mmall.vo.CartVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

@Service("iCartService")
public class CartServiceimpl implements ICartService {

    Logger logger = LoggerFactory.getLogger(CartServiceimpl.class);

    @Autowired
    CartMapper cartMapper;
    @Autowired
    ProductMapper productMapper;

    public ServerResponse<CartVo> add(Integer userId,Integer productId,Integer count){
        if (productId==null||count==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart carts = cartMapper.selectByProductUser(productId,userId);
        if (carts==null){
            Cart cart = new Cart();
            cart.setUserId(userId);
            cart.setChecked(Const.Cart.CHECKED);
            cart.setProductId(productId);
            cart.setQuantity(count);
            cartMapper.insert(cart);
        }else {
            count = count + carts.getQuantity();
            carts.setQuantity(count);
            cartMapper.updateByPrimaryKeySelective(carts);
        }
        CartVo cartVo = getCartVoLimit(userId);
        if (cartVo!=null){
            return ServerResponse.createBySuccess(cartVo);
        }
        return ServerResponse.createByErrorMessage("商品添加购物车失败");
    }

    public ServerResponse<CartVo> update(Integer userId,Integer productId,Integer count){
        if (productId==null||count==null){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        Cart carts = cartMapper.selectByProductUser(productId,userId);
        if (carts!=null){
            carts.setQuantity(count);
        }
        cartMapper.updateByPrimaryKeySelective(carts);
        CartVo cartVo = getCartVoLimit(userId);
        if (cartVo!=null){
            return ServerResponse.createBySuccess(cartVo);
        }
        return ServerResponse.createByErrorMessage("修改添加购物车失败");
    }

    public ServerResponse<Integer> selectProductCount(Integer userId){
        if (userId==null){
            return ServerResponse.createBySuccess(0);
        }
        int count = cartMapper.selectProductCount(userId);
        return ServerResponse.createBySuccess(count);
    }

    public ServerResponse<CartVo> delete(Integer userId,String productIds){
        List<String> productIdList = Splitter.on(",").splitToList(productIds);
        if (CollectionUtils.isEmpty(productIdList)){
            return ServerResponse.createByErrorCodeMessage(ResponseCode.ILLEGAL_ARGUMENT.getCode(),ResponseCode.ILLEGAL_ARGUMENT.getDesc());
        }
        int count = cartMapper.deleteCartProduct(userId,productIdList);
        if (count>0){
            CartVo cartVo = getCartVoLimit(userId);
            return ServerResponse.createBySuccess(cartVo);
        }
        return ServerResponse.createByErrorMessage("商品删除购物车失败");
    }

    public ServerResponse<CartVo> list(Integer userId){
        CartVo cartVo = getCartVoLimit(userId);
        return ServerResponse.createBySuccess(cartVo);
    }

    public ServerResponse<CartVo> check(Integer userId,Integer product,Integer check){
        int count = cartMapper.updateCheckAll(userId,product,check);
        if (count>0){
            return this.list(userId);
        }
        return ServerResponse.createByErrorMessage("选择商品失败");
    }

    private CartVo getCartVoLimit(Integer userId){
        CartVo cartVo = new CartVo();
        List<Cart> cartList = cartMapper.selectCartByUserId(userId);
        List<CartProductVo> productVoList = Lists.newArrayList();
        BigDecimal cartTotalPrice = new BigDecimal("0");
        if (cartList.size()>0){
            for (Cart cart:cartList) {
                CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setId(cart.getId());
                cartProductVo.setUserId(cart.getUserId());
                cartProductVo.setProductChecked(cart.getChecked());
                cartProductVo.setProductId(cart.getProductId());
                Product product = productMapper.selectByPrimaryKey(cart.getProductId());
                if (product!=null){
                    cartProductVo.setProductName(product.getName());
                    cartProductVo.setProductMainImage(product.getMainImage());
                    cartProductVo.setProductPrice(product.getPrice());
                    cartProductVo.setProductSubTitle(product.getSubtitle());
                    cartProductVo.setProductChecked(cart.getChecked());
                    cartProductVo.setProductStatus(product.getStatus());
                    cartProductVo.setProductStock(product.getStock());
                    // 判断库存
                    int buyLimtCount = 0;
                    if (product.getStock() >= cart.getQuantity()){
                        buyLimtCount = cart.getQuantity();
                        cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_SUCCESS);
                    }else {
                        buyLimtCount = product.getStock();
                        cartProductVo.setLimitQuantity(Const.Cart.LIMIT_NUM_FALL);
                        // 购物车中更新有效库存
                        Cart cart1 = new Cart();
                        cart1.setQuantity(buyLimtCount);
                        cart1.setId(cart.getId());
                        cartMapper.updateByPrimaryKeySelective(cart1);
                    }
                    cartProductVo.setQuantity(buyLimtCount);
                    // 计算总价
                    cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(),cart.getQuantity()));
                }
                if (cartProductVo.getProductChecked()==Const.Cart.CHECKED){
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(),cartProductVo.getProductTotalPrice().doubleValue());
                }
//                CartProductVo cartProductVo = getCartProductVo(cart,cartTotalPrice);
                productVoList.add(cartProductVo);
            }
        }
        cartVo.setCartToalPrice(cartTotalPrice);
        cartVo.setCartProductVoList(productVoList);
        cartVo.setAllChecked(cartMapper.selectCheckUser(userId)>0?false:true);
        cartVo.setImageHost("www.tangjinxin.com");
        return cartVo;
    }
}
